package leetcode.code0048;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution48 implements IDebug {

	public void rotate(int[][] matrix) {
		int len = matrix.length - 1;
		int range = matrix.length >> 1;
		for (int i = 0; i < range; i++) {
			for (int j = 0; j < range; j++) {
				swap(matrix, i, j, len);
			}
		}
		// 奇数长度最中间的没交换
		if ((matrix.length & 1) == 1) {
			for (int i = 0; i < range; i++) {
				swap(matrix, i, range, len);
			}
		}
	}

	private void swap(int[][] matrix, int i, int j, int len) {
		int endi = j;
		int endj = len - i;
		int ij = matrix[i][j];// 拿起第一个
		do {
			int ijto = matrix[endi][endj];// 保存第二个
			matrix[endi][endj] = ij;// 放下第一个
			ij = ijto;// 第二个变成第一个
			int temp = endi;
			endi = endj;// 交换坐标
			endj = len - temp;// 交换坐标
		} while (endi != j || endj != len - i);// 转到开头结束
	}

	public static void main(String[] args) {
		Solution48 so = new Solution48();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
	}

	@Override
	public void debug1() {
		String str1 = "[[1,2,3],[4,5,6],[7,8,9]]";
		int[][] r = HelpDebug.str2array1(str1);
		this.rotate(r);
		String str2 = "[[7,4,1],[8,5,2],[9,6,3]]";
		int[][] e = HelpDebug.str2array1(str2);
		HelpDebug.compare(e, r);
	}

	@Override
	public void debug2() {
		String str1 = "[[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]";
		int[][] r = HelpDebug.str2array1(str1);
		this.rotate(r);
		String str2 = "[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]";
		int[][] e = HelpDebug.str2array1(str2);
		HelpDebug.compare(e, r);
	}

	@Override
	public void debug3() {
		String str1 = "[[1]]";
		int[][] r = HelpDebug.str2array1(str1);
		this.rotate(r);
		String str2 = "[[1]]";
		int[][] e = HelpDebug.str2array1(str2);
		HelpDebug.compare(e, r);
	}

	@Override
	public void debug4() {
		String str1 = "[[1,2],[3,4]]";
		int[][] r = HelpDebug.str2array1(str1);
		this.rotate(r);
		String str2 = "[[3,1],[4,2]]";
		int[][] e = HelpDebug.str2array1(str2);
		HelpDebug.compare(e, r);
	}

}
